import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getAdminType } from '@/api/account.js'

const key = 'store:account'
export const useAccountStore = defineStore(key, {
  state: () => {
    let token = ref()
    let username = ref()
    let userid = ref()
    let avatar = ref()
    return { token, username, userid, avatar }
  },
  actions: {
    // 登录时存入用户信息
    login(token, username, userid, avatar) {
      this.token = token
      this.username = username
      this.userid = userid
      this.avatar = avatar
    },
    // 登出时清空
    logout() {
      this.token = null
      this.username = null
      this.userid = null
      this.avatar = null
      let roleStore = useRoleStore()
      roleStore.clear()
    },
  },
  getters: {
    // 获取用户信息
    getToken: state => {
      return state.token
    },
    getUserName: state => {
      return state.username
    },
    getUserId: state => {
      return state.userid
    },
    getAvatar: state => {
      return state.avatar
    },
  },
  persist: {
    key: import.meta.env.VITE_APP_ID + key,
  },
})

// export const useAccountStore = defineStore(
//   key,
//   () => {
//     let token = ref()
//     let username = ref()
//     let avatar = ref()
//     function login(usrToken) {
//       token.value = usrToken
//       username.value = 'xxx'
//       avatar.value = 'xxx'
//     }
//     return { token, username, avatar, login }
//   },
//   {
//     persist: {
//       key: import.meta.env.VITE_APP_ID + key,
//     },
//   },
// )
export default useAccountStore

export const useRoleStore = defineStore('store:role', () => {
  let accountStore = useAccountStore()

  let role = ref([])
  async function update() {
    try {
      let result = await getAdminType()
      role.value = result?.data ? [result.data] : []
      if (role.value.length === 0) {
        throw new Error('该账号无角色!')
      }
    } catch (e) {
      accountStore.logout()
      throw new Error(e?.message || e)
    }
  }
  function clear() {
    role.value = []
  }
  return { update, clear, role }
})
